package com.bawei.module_moto_circle.ui

import android.graphics.Color
import android.graphics.Paint
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.state.Empty
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_common.base.state.UILoader
import com.bawei.lib_common.base.state.UIState
import com.bawei.lib_common.observeWithLifecycle
import com.bawei.lib_common.tintDrawable
import com.bawei.lib_common.utils.ToastUtils
import com.bawei.module_moto_circle.R
import com.bawei.module_moto_circle.databinding.FragmentMotoCircleBinding
import com.bawei.module_moto_circle.databinding.LayoutCustomTabViewBinding
import com.bawei.module_moto_circle.helper.SeriesPopupMenuRvHelper
import com.bawei.module_moto_circle.model.MotoCircleNavigationItem
import com.bawei.module_moto_circle.ui.information.InformationListFragment
import com.bawei.module_moto_circle.ui.post.PostListFragment
import com.bawei.myclub.base.mvvm.view.BaseFragment
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = Router.Ui.MotoCircleFragment)
class MotoCircleFragment : BaseFragment<MotoCircleViewModel, FragmentMotoCircleBinding>() {

    override val mLayoutResId: Int
        get() = R.layout.fragment_moto_circle

    override val mViewModel: MotoCircleViewModel by viewModels()

    override val mPageCanBack: Boolean
        get() = false

    private var mPostAdapter: ScreenSlidePagerAdapter? = null

    private var mSelectedPosition: Int = 0

    private lateinit var mUiLoader: UILoader

    private var mediator: TabLayoutMediator? = null

    override fun initView() {
        initUILoader()
    }

    private fun initUILoader() {
        mUiLoader = object : UILoader(requireContext()) {
            override fun loadSuccessView(container: ViewGroup?): View {
                return View(context)
            }

        }.apply { updateState(UIState.LOADING) }
        mBinding.lContainer.addView(mUiLoader)

    }

    override fun initListener() {
        //订阅tab数据
        mViewModel.navigationState.observeWithLifecycle(this) {
            when (it) {
                is Success -> {
                    handleNavigationData()
                    mUiLoader.updateState(UIState.SUCCESS)
                }

                is Empty -> {
                    mUiLoader.updateState(UIState.EMPTY)
                }

                is Failed -> {
                    mUiLoader.updateState(UIState.NETWORK_ERROR)
                }

                is Loading -> {
                    mUiLoader.updateState(UIState.LOADING)
                }

            }
        }
        //点击重试
        mUiLoader.setOnRetryClickListener {
            initData()
        }
        //点击搜索
        mBinding.lSearch.setOnClickListener {
            ARouter.getInstance()
                .build(Router.Ui.SearchActivity)
                .withString("search_type","all")
                .navigation()
        }
    }

    override fun initData() {
        //请求tab数据
        mViewModel.getFixedNavigationItem()
    }

    /**
     * 加载tab数据以及viewpager
     */
    private fun handleNavigationData() {
        initViewPager()
    }

    private fun initViewPager() {
        //适配器
        mPostAdapter = ScreenSlidePagerAdapter(mViewModel.mNavigationItem, this)
        mBinding.vp.adapter = mPostAdapter
        //默认选中
        val default = mViewModel.mNavigationItem.find { it.defaultStatus == 1 } //默认选中tab
        mSelectedPosition = if (default == null) 0 else mViewModel.mNavigationItem.indexOf(default)
        mBinding.vp.currentItem = mSelectedPosition
        //预加载机制
        mBinding.vp.offscreenPageLimit = 1
        //viewpager和tablayout联动
        mBinding.vp.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mSelectedPosition = position
                //更新tab选中
            }
        })
        //自定义tab样式
        mediator = TabLayoutMediator(
            mBinding.tabLayout,
            mBinding.vp,
            true,
            true
        ) { tab, position ->  //默认样式
            //自定义
            val tabView = DataBindingUtil.inflate<LayoutCustomTabViewBinding>(
                layoutInflater,
                R.layout.layout_custom_tab_view,
                null,
                false
            )
            if (position >= mViewModel.mNavigationItem.size) {
                return@TabLayoutMediator
            }
            val navigation = mViewModel.mNavigationItem[position]
            //判断二级目录，是否选中
            if (navigation.modelList == null || !navigation.modelList.any { it.checked }) {
                tabView.tab.text = navigation.title
            } else {
                tabView.tab.text = navigation.modelList.find { it.checked }?.name
            }
            tabView.ivArrow.visibility =
                if (navigation.modelList == null) View.GONE else View.VISIBLE
            //点击事件处理
            tabView.lTab.setOnClickListener {
                if (tab.isSelected) {//选中，展开二级目录
                    if (navigation.modelList != null) {
                        showPopupList(tabView.lTab, navigation)
                    }
                } else {//未选中--》选中，展开二级目录
                    tab.select()
                    if (navigation.modelList != null) {
                        Handler(Looper.getMainLooper()).postDelayed({
                            showPopupList(
                                tabView.lTab,
                                navigation
                            )
                        }, 400)
                    }
                }
            }
            tab.customView = tabView.root
        }
        mediator?.attach()
    }


    private val popupMenuRvHelper by lazy {
        SeriesPopupMenuRvHelper(layoutInflater) { navigationId, modelItem ->
            val clickNavigation =
                mViewModel.mNavigationItem.find { it.navigationId == navigationId }
            clickNavigation?.modelList!!.forEach {
                it.checked = modelItem.modelId == it.modelId
            }
            mPostAdapter?.notifyDataSetChanged()
            setTabViewStyle(mSelectedPosition)
        }
    }

    private fun setTabViewStyle(defaultPosition: Int) {
        mViewModel.mNavigationItem.forEachIndexed { index, _ ->
            mBinding.tabLayout.run {
                val binding = getTabAt(index)?.customView?.let {
                    DataBindingUtil.getBinding<LayoutCustomTabViewBinding>(it)
                }
                if (defaultPosition == index) {
                    binding?.tab?.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            com.bawei.lib_common.R.color.color_d8000f
                        )
                    )
                    binding?.tab?.paint?.style = Paint.Style.FILL_AND_STROKE
                    val drawable = ContextCompat.getDrawable(context, R.mipmap.ic_triangle)
                    val tintDrawable = tintDrawable(drawable, Color.parseColor("#FF919191"))
                    binding?.ivArrow?.setImageDrawable(tintDrawable)
                    binding?.tab?.paint?.strokeWidth = 0.8f
                } else {
                    binding?.tab?.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            com.bawei.lib_common.R.color.color_101010
                        )
                    )
                    binding?.tab?.paint?.style = Paint.Style.FILL_AND_STROKE
                    val drawable = ContextCompat.getDrawable(context, R.mipmap.ic_triangle)
                    val tintDrawable = tintDrawable(drawable, Color.parseColor("#FF919191"))
                    binding?.ivArrow?.setImageDrawable(tintDrawable)
                    binding?.tab?.paint?.strokeWidth = 0f
                }


            }
        }
    }

    private fun showPopupList(tabView: View, navigation: MotoCircleNavigationItem) {
        popupMenuRvHelper.bindItems(navigation.navigationId, navigation.modelList!!)
        popupMenuRvHelper.show(tabView)
    }


    override fun onDestroy() {
        super.onDestroy()
        //防止内存泄漏
        mediator?.detach()
        mediator = null
    }

    private inner class ScreenSlidePagerAdapter(
        private val item: List<MotoCircleNavigationItem>,
        fa: Fragment
    ) : FragmentStateAdapter(fa) {
        override fun getItemCount(): Int {
            return item.size
        }

        override fun getItemId(position: Int): Long {
            return item[position].navigationId.toLong()
        }

        override fun createFragment(position: Int): Fragment {
            return when (item[position].type) {
                1 -> {
                    val modelItem = item[position].modelList?.find { it.checked }
                    if (modelItem?.modelId == "10001_01") {
                        ToastUtils.showLong(requireActivity(), "点击了${modelItem?.name}")
                        PostListFragment.newInstance(sortType = "hot")
                    } else {
                        ToastUtils.showLong(requireActivity(), "点击了${modelItem?.name}")
                        PostListFragment.newInstance(sortType = "hot")
                    }
                }

                2 -> PostListFragment.newInstance(sortType = "new")
                3 -> InformationListFragment()
                4 -> PostListFragment.newInstance(ifFocus = 1)
                else -> PostListFragment()
            }
        }

    }


}